import paho.mqtt.client as mqtt
from PyQt5.QtCore import QObject, pyqtSignal

from src.utils.log import log
from src.widget.DialogToInfo import DialogToInfo

""" 封装mqtt回调函数"""


class MQTTHandler(QObject):
    showDialogSignal = pyqtSignal(str)  # 定义信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.showDialogSignal[str].connect(self.showToast)  # 确保使用QueuedConnection

    def handleStrMsgCallback(self, client: mqtt.Client, userdata, msg: mqtt.MQTTMessage):
        """ 处理字符串消息回调函数"""
        try:
            log = userdata['log']
            info = msg.payload.decode()
            log.info(f"已收到消息: {info}")
            # 发射信号，确保它在主线程中处理
            self.showDialogSignal[str].emit(info)
        except Exception as e:
            raise Exception(f"handleStrMsgCallback 出现错误: {e}")

    def showToast(self, msg):
        """ 信号触发弹窗"""
        try:
            DialogToInfo().Info(info=msg)
        except Exception as e:
            log.error(f"弹窗无法显示:{e}")
